package com.mtjx.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.StringUtils;
import com.mtjx.entitys.LoginUser;
import com.mtjx.utils.JwtUtil;
import com.mtjx.utils.RedisCache;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author 33117
 * @version 1.0
 * @data 2025/8/29 11:07
 * 过滤器
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            // 放行
            filterChain.doFilter(request, response);
            return;
        }
        // 解析token
        String userid;
        try {
            userid = JwtUtil.parseJWT(token).getSubject();
        } catch (Exception e) {
            throw new RuntimeException("Token非法");
        }
        // 从redis获取用户信息
        String key = "login:" + userid;
        Object obj = redisCache.getCacheObject(key);
        LoginUser loginUser = null;
        //通过instanceof JSONObject检查从Redis获取的对象类型，确保只有在对象是JSONObject类型时才进行转换
        if (obj instanceof JSONObject) {
            // 使用JSON.parseObject()方法将JSONObject转换为LoginUser对象，这是典型的JSON反序列化操作
            loginUser = JSON.parseObject(((JSONObject) obj).toJSONString(), LoginUser.class);
        }
        if (Objects.isNull(loginUser)) {
            throw new RuntimeException("用户未登录");
        }
        // 存入SecurityContextHolder
        // 获取权限信息，添加到登录认证中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 放行
        filterChain.doFilter(request, response);
    }
}
